package com.runa.monitor.platinterface.backwork.impl;

import com.runa.monitor.platinterface.backwork.function.WriteBack;
import com.runa.monitor.comm.dto.LegacyWsMessage;
import com.runa.persistence.SerializeUtil;

import javax.websocket.Session;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WebSocketWriteBack implements WriteBack<String, String> {

    private final Session session;

    public WebSocketWriteBack(Session session) {
        this.session = session;
    }

    @Override
    public void writeBack(String s, String content, String error) {
        if (session.isOpen()) {
            LegacyWsMessage wsMessage = new LegacyWsMessage();
            wsMessage.setCmd("Rsp_RecvBuffer");
            wsMessage.setNetEquSerialNo(s);
            Map<String, Object> data = new HashMap<>();
            data.put("Message", error);
            data.put("RecvBuffer", content);
            data.put("Result", error == null);
            wsMessage.setData(data);
            try {
                session.getBasicRemote().sendText(SerializeUtil.obj2json(wsMessage));
            } catch (IOException e) {
                
            }
        }
    }
}
